package com.mjf.cjt.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mjf.cjt.domain.MjfManufactureOrder;
import com.mjf.cjt.domain.MjfManufactureOrderDetails;
import com.mjf.cjt.domain.MjfManufactureOrderDetailsMaterial;
import com.mjf.cjt.mapper.MjfManufactureOrderMapper;
import com.mjf.cjt.service.AsyncTMService;
import com.mjf.cjt.service.IMjfManufactureOrderDetailsMaterialService;
import com.mjf.cjt.service.IMjfManufactureOrderDetailsService;
import com.mjf.cjt.service.IMjfManufactureOrderService;
import com.mjf.cjt.vo.MjfManufactureOrderVo;
import com.mjf.cjt.vo.ProductOrderVo;
import com.mjf.common.utils.DateUtils;
import com.mjf.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 生成加工单 服务实现类
 * </p>
 *
 * @author
 * @since 2025-04-05
 */
@Service
public class MjfManufactureOrderServiceImpl extends ServiceImpl<MjfManufactureOrderMapper, MjfManufactureOrder> implements IMjfManufactureOrderService {

    @Autowired
    private MjfManufactureOrderMapper mjfManufactureOrderMapper;
    @Autowired
    private AsyncTMService asyncTMService;
    @Autowired
    private IMjfManufactureOrderDetailsService mjfManufactureOrderDetailsService;
    @Autowired
    private IMjfManufactureOrderDetailsMaterialService mjfManufactureOrderDetailsMaterialService;

    /**
     * 分页查询加工单及其明细
     * @return 查询结果
     */
    @Override
    public PageInfo<MjfManufactureOrderVo> queryManufactureOrderWithDetails(MjfManufactureOrderVo vo) {
        // 开启分页
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        // 调用 Mapper 查询
        List<MjfManufactureOrderVo> list = mjfManufactureOrderMapper
        		.selectManufactureOrderWithDetails(vo.getStartDateStr(),
        				vo.getEndDateStr(), vo.getCode(), vo.getReviser(),
        				vo.getInventoryName(), vo.getDetailsSaleOrderCode());
        // 封装分页结果
        return new PageInfo<>(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getProductionRemote(String start, String end) {
        try {
            List<ProductOrderVo> productionRemote = asyncTMService.getDeliveryOrderFromRemote(start, end);
            if (CollectionUtil.isNotEmpty(productionRemote)) {
                // 按明细行ID分组
                Map<Long, List<ProductOrderVo>> voMap =
                        productionRemote.stream().collect(Collectors.groupingBy(ProductOrderVo::getId));
                List<MjfManufactureOrder> mjfManufactureOrders = new ArrayList<>();
                List<MjfManufactureOrderDetails> mjfManufactureOrderDetails = new ArrayList<>();
                List<MjfManufactureOrderDetailsMaterial> manufactureOrderDetailsMaterials = new ArrayList<>();
                for (Map.Entry<Long, List<ProductOrderVo>> entry : voMap.entrySet()) {
                    // 主单
                    MjfManufactureOrder order = new MjfManufactureOrder();
                    order.setId(entry.getValue().get(0).getId());
                    order.setCode(entry.getValue().get(0).getCode());
                    if (StringUtils.isNotBlank(entry.getValue().get(0).getVoucherdate())) {
                        order.setVoucherDate(DateUtils.parseDate(entry.getValue().get(0).getVoucherdate()
                            .replace("/", "-")));
                    }
                    order.setPerson(entry.getValue().get(0).getPerson_name());
                    order.setPubuserdefnvc7(entry.getValue().get(0).getPubuserdefnvc7());
                    order.setPubuserdefnvc8(entry.getValue().get(0).getPubuserdefnvc8());
                    mjfManufactureOrders.add(order);
                    // 按明细ID分组
                    Map<Long, List<ProductOrderVo>> detailsMap = entry.getValue().stream().collect(Collectors.groupingBy(ProductOrderVo::getManufactureorderdetails_id));
                    for (Map.Entry<Long, List<ProductOrderVo>> detailsEntry : detailsMap.entrySet()) {
                        // 明细
                        ProductOrderVo orderDetail = detailsEntry.getValue().get(0);
                        MjfManufactureOrderDetails details = new MjfManufactureOrderDetails();
                        details.setId(orderDetail.getManufactureorderdetails_id());
                        details.setMId(entry.getValue().get(0).getId());
                        details.setSaleOrderCode(orderDetail.getManufactureorderdetails_saleordercode());
                        details.setWarehouse(orderDetail.getManufactureorderdetails_warehouse_name());
                        details.setInventoryName(orderDetail.getManufactureorderdetails_inventory_name());
                        details.setInventoryCode(orderDetail.getManufactureorderdetails_inventory_code());
                        details.setInventoryPriUserDefDecm1(orderDetail.getManufactureorderdetails_inventory_priuserdefnvc1());
                        details.setInventorySpecification(orderDetail.getManufactureorderdetails_inventory_specification());
                        details.setUnitName(orderDetail.getManufactureorderdetails_unit_name());
                        details.setQuantity(orderDetail.getManufactureorderdetails_quantity());
                        details.setPubuserdefnvc2(orderDetail.getManufactureorderdetails_pubuserdefnvc2());
                        mjfManufactureOrderDetails.add(details);
                        // 材料明细
                        for (ProductOrderVo productOrderVo : detailsEntry.getValue()) {
                            MjfManufactureOrderDetailsMaterial material  = new MjfManufactureOrderDetailsMaterial();
                            if (productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_id() != null) {
                                material.setId(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_id());
                                material.setMdId(orderDetail.getManufactureorderdetails_id());
                                material.setInventoryCode(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_inventory_code());
                                material.setInventoryName(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_inventory_name());
                                material.setInventorySpecification(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_inventory_specification());
                                material.setUnitId(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_inventory_unit_id());
                                material.setUnitName(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_inventory_unit_name());
                                material.setQuantity(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_quantity());
                                material.setBatch(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_batch());
                                material.setMemo(productOrderVo.getManufactureorderdetails_manufactureordermaterialdetails_memo());
                                manufactureOrderDetailsMaterials.add(material);
                            }
                        }
                    }

                    // 清除已存在数据
                    removeByIds(mjfManufactureOrders.stream().map(MjfManufactureOrder::getId).collect(Collectors.toList()));
                    mjfManufactureOrderDetailsService.removeByIds(mjfManufactureOrderDetails.stream().map(MjfManufactureOrderDetails::getId)
                        .collect(Collectors.toList()));
                    mjfManufactureOrderDetailsMaterialService.removeByIds(manufactureOrderDetailsMaterials.stream().map(MjfManufactureOrderDetailsMaterial::getId).collect(Collectors.toList()));
                    // 保存
                    saveBatch(mjfManufactureOrders);
                    mjfManufactureOrderDetailsService.saveBatch(mjfManufactureOrderDetails);
                    mjfManufactureOrderDetailsMaterialService.saveBatch(manufactureOrderDetailsMaterials);
                }
            }
        } catch (ChanjetApiException e) {
            throw new RuntimeException(e);
        }
    }
}
